package coms.mianshi.serializable;

import java.io.*;

/**
 * @program: item_02
 * @description: 普通序列化
 * Serializable接口是一个标记接口，不用实现任何方法。一旦实现了此接口，该类的对象就是可序列化的。
 * 同一对象序列化多次，会将这个对象序列化多次吗？答案是否定的
 * @author: LL
 * @create: 2021-03-02 17:44
 */
public class Person implements Serializable {

    private String name;
    private int age;

    public Person(final String name, final int age) {
        this.name = name;
        this.age = age;
    }

    public Person() {
    }

    public String getName() {
        return this.name;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public int getAge() {
        return this.age;
    }

    public void setAge(final int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + this.name + '\'' +
                ", age=" + this.age +
                '}';
    }

    /**
     * 序列化
     * 步骤一：创建一个ObjectOutputStream输出流；
     * 步骤二：调用ObjectOutputStream对象的writeObject输出可序列化对象。
     */
    public void test() throws IOException {
        //创建一个ObjectOutputStream输出流
        final ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\a.txt"));
        //将对象序列化到文件S
        final Person person = new Person("测试", 20);
        oos.writeObject(person);

        person.setAge(50);
        oos.writeObject(person);
    }

    /**
     * 反序列化
     * 步骤一：创建一个ObjectInputStream输入流；
     * 步骤二：调用ObjectInputStream对象的readObject()得到序列化的对象。
     */
    public void test2() throws IOException, ClassNotFoundException {
        //创建一个ObjectInputStream输入流
        final ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\a.txt"));
        final Person brady1 = (Person) ois.readObject();
        final Person brady2 = (Person) ois.readObject();
        System.out.println(brady1);
        System.out.println(brady2);
    }

    public static void main(final String[] args) throws IOException, ClassNotFoundException {
        final Person person = new Person();
        person.test();
        person.test2();

    }
}
